package net.zjitc.controller;

import net.zjitc.common.ServiceResponse;
import net.zjitc.pojo.Category;
import net.zjitc.pojo.Condition;
import net.zjitc.pojo.Products;
import net.zjitc.service.ProductsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author jinliwei
 * @Date 2019/4/2 23:48
 **/
@Controller
@RequestMapping("/manage/products")
public class ProductsController {
    @Autowired
    ProductsService productsService;

    @RequestMapping("/listProduct")
    public String findAll(Model model){
        List<Products> plist = productsService.findAllProducts();
        List<Category> clist = productsService.findAllCategory();
        model.addAttribute("plist",plist);
        model.addAttribute("clist",clist);
        return "/admin/products/list.jsp";
    }

    @RequestMapping("/addProductsView")
    public String addProductView(Model model){
        List<Category> clist = productsService.findAllCategory();
        model.addAttribute("clist",clist);
        return "/admin/products/add.jsp";
    }

    @RequestMapping("/addProduct")
    @ResponseBody
    public ServiceResponse addProduct(Products products,
                                      @RequestParam(required = false,value = "file") MultipartFile file,
                                      HttpServletRequest request){
        return productsService.addProduct(products,file,request);
    }

    @RequestMapping("/findProductById")
    public String findProductById(String id,Model model){
        Products list = productsService.findProductById(id);
        List<Category> clist = productsService.findAllCategory();
        model.addAttribute("p",list);
        model.addAttribute("clist",clist);
        return "/admin/products/edit.jsp";
    }

    //修改（未完成）
    @RequestMapping("/editProduct")
    @ResponseBody
    public ServiceResponse editProduct(Products products,
                                       @RequestParam(required = false,value = "file") MultipartFile file,
                                       HttpServletRequest request){
        return productsService.editProduct(products,file,request);
    }

    //删除
    @RequestMapping("/deleteProduct")
    public String deleteProduct(String id,Model model){
        int i = productsService.deleteProduct(id);
        return "redirect:/manage/products/listProduct.do";
    }

    @RequestMapping("/searchByCondition")
    @ResponseBody
    public List<Products> searchByCondition(Condition condition){
        List<Products> plist = productsService.searchByCondition(condition);
        return plist;
    }


}
